/*
 *  Copyright (C) 2005-2007 Renier Roth
 *  www.renier.de
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package de.renier.vdr.channel.editor.actions;

import java.awt.event.ActionEvent;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import de.renier.vdr.channel.editor.ChannelEditor;

/**
 * AbstractSortAction
 * 
 * @author <a href="mailto:editor@renier.de">Renier Roth</a>
 */
public abstract class AbstractSortAction extends AbstractAction {

  public AbstractSortAction(String title) {
    super(title);
  }

  /*
   * (non-Javadoc)
   * 
   * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
   */
  public void actionPerformed(ActionEvent e) {
    TreePath treePath = ChannelEditor.application.getChannelListingPanel().getLeadSelectionPath();
    if (treePath != null) {
      DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent();
      // if we are root do sort on all subnodes as well
      if (node.isRoot()) {
        Enumeration enumer = node.children();
        while (enumer.hasMoreElements()) {
          doSorting((DefaultMutableTreeNode) enumer.nextElement());
        }
        doSorting(node);
      } else {
        doSorting(node);
      }
      // notify structure change
      ChannelEditor.application.getChannelListingPanel().treeNodeStructureChanged(node);
    }
  }

  /**
   * @param node
   */
  private void doSorting(DefaultMutableTreeNode node) {
    Enumeration enumer = node.children();
    List sortList = new LinkedList();
    while (enumer.hasMoreElements()) {
      sortList.add(enumer.nextElement());
    }
    // sort the list
    Collections.sort(sortList, createSortComparator());
    // put sortet Nodes back to parent node
    Iterator it = sortList.iterator();
    while (it.hasNext()) {
      node.add((DefaultMutableTreeNode) it.next());
    }
  }

  protected abstract Comparator createSortComparator();

}
